<?php

class ServiceController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
		array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('index','view','create','update','admin','delete','startProcess','copyService', 
				'allocateJob', 'finishJob', 'exportRecords','ajaxSearchStore','ajaxSearchProductNameModel', 
				'ajaxSearchProductNames','ajaxSearchProductModels', 'ajaxSearchProduct'),
				'users'=>array('admin'),
		),
		array('deny',  // deny all users
				'users'=>array('*'),
		),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Service;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Service']))
		{
			$model->attributes=$_POST['Service'];
			$model->status=Service::STATUS_NEW;
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Service']))
		{
			$model->attributes=$_POST['Service'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Service',array(
      		'criteria'=>array(
          		'order'=>'id DESC',
			),)			
		);
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new ServiceSearch('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['ServiceSearch']))
			$model->attributes=$_GET['ServiceSearch'];
		$this->render('admin',array(
			'model'=>$model,
		));
	}

	public function actionCopyService($id){
		$model=$this->loadModel($id);
		$newModel=new Service;
		$newModel->attributes=$model->attributes;


		if($newModel->save()){
			$message="Record Copied. New reference ID is: ".$newModel->id;
			Yii::app()->user->setFlash('service_admin_message',$message);
			$this->redirect(array('admin'));

		}else{
			$message="Failed to copy record.";
			Yii::app()->user->setFlash('service_admin_message',$message);
		}
	}

	public function actionStartProcess($id) {
		$model=$this->loadModel($id);
		if($model->status!=Service::STATUS_NEW){
			throw new CHttpException(403,'Service is not NEW. Cannot start processing.');
		}
		if(Yii::app()->request->isPostRequest){
			$message='Processed Action:';
			$transaction=Yii::app()->db->beginTransaction();
			try{
				$model->status=Service::STATUS_PROCESSING;
				if($model->save()){
					
					//Set the email will be sent.
					$mailMessage = new YiiMailMessage;
					$mailMessage->view = 'startProcessSendToStore';
					$mailMessage->setBody(array('service'=>$model), 'text/html');
					$mailMessage->setSubject($model->firstName.' '.$model->LastName.' - #'.$model->id);
					$mailMessage->from = Yii::app()->params['adminEmail'];
					
					if($storeEmail=$model->store->contactEmail){						
						$mailMessage->addTo($storeEmail);
						$message.='<br />Sent email to store email: '.$storeEmail;
					}
					if($managerEmail=$model->store->managerEmail){
						$mailMessage->addTo($managerEmail);
						$message.='<br />Sent email to store manager email: '.$model->store->managerEmail;
					}
					//send email to  store and manager email.
					Yii::app()->mail->send($mailMessage);
					$message.='<br />Started process for Serive #'.$model->id;
				}else{
					$message='Failed to change status of servie.';
				}
				Yii::app()->user->setFlash('service_admin_message',$message);
				$transaction->commit();
				$this->redirect(array('admin'));

			}catch(Exception $e){
				Yii::app()->user->setFlash('service_admin_message','Failed to process the transaction. The message was: '.$e->getMessage());
				$transaction->rollBack();
				$this->redirect(array('admin'));
			}
		}else{
			// not post, display confirm form
			$this->render('startProcess',array(
				'model'=>$model,
			));
		}
	}

	public function actionAllocateJob($id) {
		$model=$this->loadModel($id);
		if($model->status!=Service::STATUS_PROCESSING){
			throw new CHttpException(403,'Service is not PROCESSING. Cannot start allocating job.');
		}
		if(Yii::app()->request->isPostRequest){
			$message='Job Allocation Action:';
			$transaction=Yii::app()->db->beginTransaction();
			try {
				$model->attributes=$_POST['Service'];
				$model->status=Service::STATUS_JOB_ALLOCATED;
				$model->dateCommenced = new CDbExpression('NOW()');
				if($model->save()){
					$model=$this->loadModel($id);
					
					//Send to store.
					if($storeEmail=$model->store->contactEmail){
						$mailMessage = new YiiMailMessage;
						$mailMessage->view = 'allocateJobSendToStore';
						$mailMessage->setBody(array('service'=>$model), 'text/html');
						$mailMessage->setSubject($model->firstName.' '.$model->LastName.' - #'.$model->id);
						$mailMessage->from = Yii::app()->params['adminEmail'];
						$mailMessage->to = $storeEmail;
						$message.='<br />Sent email to Store email: '.$storeEmail;	
						//send email to  store email.
						Yii::app()->mail->send($mailMessage);
					}
					
					//Send to technician.
					$mailMessage = new YiiMailMessage;
					$mailMessage->view = 'allocateJobSendToTechnician';
					$mailMessage->setBody(array('service'=>$model), 'text/html');
					$mailMessage->setSubject($model->firstName.' '.$model->LastName.' - #'.$model->id);
					$mailMessage->from = Yii::app()->params['adminEmail'];
					$mailMessage->to = $model->technician->email;
					
					$filename=$model->firstName.' '.$model->LastName.' - #'.$model->id.'.html';
					//$viewPath = Yii::getPathOfAlias(Yii::app()->mail->viewPath.'.attachmentToTechnician');
					$body = $this->renderPartial('//email/attachmentToTechnician',  array('service'=>$model), true);	
					$attachment=new Swift_Attachment($body, $filename,'text/html');
					$mailMessage->attach($attachment);
					
					$message.='<br />Sent email to Technician email: '.$model->technician->email;	
					//send email to  store and manager email.
					Yii::app()->mail->send($mailMessage);					
					$message.='<br />Allocated Job for Serive #'.$model->id;
				}else{
					$message='Failed to change status of servie.';
				}
				Yii::app()->user->setFlash('service_admin_message',$message);
				$transaction->commit();
				$this->redirect(array('admin'));
			}catch(Exception $e){
				Yii::app()->user->setFlash('service_admin_message','Failed to process the transaction. The message was: '.$e->getMessage());
				$transaction->rollBack();
				$this->redirect(array('admin'));
			}
		}else{
			// not post, display confirm form
			$this->render('allocateJob',array(
				'model'=>$model,
			));
		}
	}
	
	public function actionFinishJob($id) {
		$model=$this->loadModel($id);
		if($model->status!=Service::STATUS_JOB_ALLOCATED){
			throw new CHttpException(403,'Service is not JOB_ALLOCATED. Cannot finish the job.');
		}
		if(Yii::app()->request->isPostRequest){
			$message='Finished Job Action:';
			$model->status=Service::STATUS_FINISHED;
			$model->dateCompleted = new CDbExpression('NOW()');
			if($model->save()){	
				$message.='<br />Finished Job for Serive #'.$model->id;
			}else{
				$message='Failed to change status of servie.';
			}
			Yii::app()->user->setFlash('service_admin_message',$message);
			$this->redirect(array('admin'));
		}else{
			// not post, display confirm form
			$this->render('finishJob',array(
				'model'=>$model,
			));
		}
	}
	
	public function actionExportRecords(){
		if(!isset($_POST['exportServiceRecords'])){
			throw new CHttpException(403,'No array of records passed to export!');
		}
		$service_records=explode(',', $_POST['exportServiceRecords']);
		
		//if(!is_array($service_records)){
		//	throw new CHttpException(403,'No array of records passed to export!');
		//}
		$criteria=new CDbCriteria();
		$criteria->addInCondition('id',$service_records);
		$services=Service::model()->findAll($criteria);
		
		$out = fopen('php://output', 'w');
		
		header("Content-type: application/vnd.ms-excel");
		header("Content-Disposition: attachment; filename=service_".date('Ymd').".csv" );
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
		header("Pragma: public");		
		fputcsv($out, Service::model()->attributeLabels());
		foreach($services as $service){
			if($service->technicianId != null)
				$service->technicianId = $service->technician->name;
			if($service->stairs != null)
				$service->stairs = DataUtil::getOptionYesNoEmpty($service->stairs);
			if($service->chargeApplicable != null)
				$service->chargeApplicable = DataUtil::getOptionYesNoEmpty($service->chargeApplicable);
			if($service->fundsRecovered != null)
				$service->fundsRecovered=DataUtil::getOptionYesNoEmpty($service->fundsRecovered);
			if($service->paymentType != null)
				$service->paymentType=$service->servicePayment->paymentType;
			if($service->technicainPaid != null)
				$service->technicainPaid=DataUtil::getOptionYesNoEmpty($service->technicainPaid);
			if($service->workCarriedOut != null)
				$service->workCarriedOut=DataUtil::getOptionYesNoEmpty($service->workCarriedOut);
			$service->warranty=DataUtil::getOptionYesNoEmpty($service->warranty);
			$service->productId = $service->product->name."(".$service->product->model.")";
			$service->storeId=$service->store->name."(".$service->store->code.")";
			$service->status=Service::getStatusArray($service->status);
			fputcsv($out, $service->attributes);
		}
		fclose($out);
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Service::model()->findByPk((int)$id);
		if($model===null)
		throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='service-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	public function actionAjaxSearchProductNameModel(){
		$data=Product::model()->findAll('type=:type',
		array(':type'=>$_POST['product_type']));
		
		foreach($data as $item)
		{
			echo CHtml::tag('option',
			array('value'=>$item->id),
				CHtml::encode($item->name."(".$item->model.")"),true);
		}
	}	
	
	
	public function actionAjaxSearchProductNames(){
		$data=Product::model()->findAll('type=:type',
			array(':type'=>$_POST['product_type']));
		
		$names=CHtml::listData($data,'name','name');
		$htmlOptions = array('empty'=>'');
		echo CHtml::listOptions('', $names, $htmlOptions);
	}

	public function actionAjaxSearchProductModels(){
		$type = $_POST['product_type'];
		$name = $_POST['product_name'];
		
		$data=Product::model()->findAll(
				array(
					'select'=>'id, model',
					'condition'=>'name=:name AND type=:type',
					'params'=>array(':type'=>$type, ':name'=>$name),
					'distinct'=>true
				));
		
		$data=CHtml::listData($data,'id','model');
		$htmlOptions = array('empty'=>'');
		echo CHtml::listOptions('', $data, $htmlOptions);
	}
	
	
	public function actionAjaxSearchStore(){
		if(Yii::app()->request->isAjaxRequest && isset($_GET['term']))
		{
			/* q is the default GET variable name that is used by
			 / the autocomplete widget to pass in user input
			 */
			$name = $_GET['term'];
			// this was set with the "max" attribute of the CAutoComplete widget
			$limit = isset($_GET['limit'])?min($_GET['limit'], 50):50;
			$criteria = new CDbCriteria;
			$criteria->condition = "code LIKE :sterm OR name like :sterm";
			$criteria->params = array(":sterm"=>"%$name%");
			$criteria->limit = $limit;
			$storeArray = Store::model()->findAll($criteria);
			$returnVal = array();
			foreach($storeArray as $store)
			{
				$returnVal[] = array('label'=> $store->getAttribute('name').
					'('.$store->getAttribute('code').')',
					'id'=>$store->getAttribute('id'),
					'address'=>$store->getAttribute('address'),
					'city'=>$store->getAttribute('city'),
					'state'=>$store->getAttribute('state'),
					'postcode'=>$store->getAttribute('postcode'),
					'contactName'=>$store->getAttribute('contactName'),
					'contactPhone'=>$store->getAttribute('contactPhone'),
					'contactEmail'=>$store->getAttribute('contactEmail')
				);
			}
			//          header("Cache-Control: no-cache, must-revalidate");
			//          header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
			echo CJSON::encode($returnVal);
		}
	}

	public function actionAjaxSearchProduct(){
		if(Yii::app()->request->isAjaxRequest && isset($_GET['term']))
		{
			/* q is the default GET variable name that is used by
			 / the autocomplete widget to pass in user input
			 */
			$name = $_GET['term'];
			// this was set with the "max" attribute of the CAutoComplete widget
			$limit = isset($_GET['limit'])?min($_GET['limit'], 50):50;
			$criteria = new CDbCriteria;
			$criteria->condition = "name LIKE :sterm OR model like :sterm OR type LIKE :sterm";
			$criteria->params = array(":sterm"=>"%$name%");
			$criteria->limit = $limit;
			$productArray = Product::model()->findAll($criteria);
			$returnVal = array();
			foreach($productArray as $product)
			{
				$returnVal[] = array(
					'label'=>$product->name."(".$product->model.") - ".$product->type,
					'id'=>$product->id,
				);
			}
			echo CJSON::encode($returnVal);
		}
	}
}
